using System;
using System.Collections;
using BehaviorDesigner.Runtime.Tasks.Unity.UnityInput;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Rendering.Universal;

public class PlayerController : MonoBehaviour
{
    #region useless

    [HideInInspector] public float jumpForce;
    private PhysicsCheck check => GetComponent<PhysicsCheck>();

    [HideInInspector] public bool isLightHide;
    [HideInInspector] public bool isSoldierHide;
    [HideInInspector] public bool canLightHide = true;
    [HideInInspector] public bool canSoldierHide = true;
    [HideInInspector] public bool canJump = true;
    [HideInInspector] public bool canMove = true;

    private bool isClimbing;
    private float gravityScale;
    private bool stairJump;

    #endregion
    
    private PlayerInput playerInput;
    [Header("移动速度")]
    [HideInInspector]public float speed;
    private Vector2 dir;
    private Vector2 lastDir;
    [HideInInspector] public Rigidbody2D rb;

    public DataDetails_SO DataDetails;

    public Light2D Light;
    private Camera mainCamera;
    private Vector3 mouseDir;

    private Animator anim => GetComponent<Animator>();
    private bool isMoving;

    private CapsuleCollider2D _coll => GetComponent<CapsuleCollider2D>();
    private Vector2 size;

    public Transform startPos;

    private void Awake()
    {
        DataDetails.ReloadData();
        
        playerInput = new PlayerInput();
        rb = GetComponent<Rigidbody2D>();
        speed = Settings.playerSpeed;
        jumpForce = Settings.jumpForce;
        
        playerInput.Gameplay.Jump.started += Jump;
        mainCamera = Camera.main;
        size = _coll.bounds.size;
    }
    

    private void OnEnable()
    {
        playerInput.Enable();
        EventHandler.StartDive += OnStartDive;
        EventHandler.EndDive += OnEndDive;
        EventHandler.CarryPeople += OnCarryPeople;
    }

    private void OnDisable()
    {
        playerInput.Disable();
        EventHandler.StartDive -= OnStartDive;
        EventHandler.EndDive -= OnEndDive;
        EventHandler.CarryPeople -= OnCarryPeople;
    }

    private void Update()
    {
        if(canMove) dir = playerInput.Gameplay.Move.ReadValue<Vector2>();
        ControlLight();
        ChangeCollider();
    }
    
    private void FixedUpdate()
    {
        Move();
    }

    private void Move()
    {
        isMoving = dir != Vector2.zero;
        if (!AirConsumeManager.Instance.stopConsume)
        {
            rb.velocity = new Vector2(dir.x * speed * Time.deltaTime, dir.y * speed * Time.deltaTime);
        }
        else
        {
            Debug.Log("1");
            rb.velocity = new Vector2(0, dir.y * speed * Time.deltaTime);
        }

        if (isMoving)
        {
            anim.SetFloat("DirX", dir.x);
            anim.SetFloat("DirY", dir.y);
        }
        anim.SetBool("isMoving", isMoving);
    }

    private void ControlLight()
    {
        // 获取鼠标在屏幕空间的坐标（z 轴设为与光源相同的深度）
        Light.transform.localScale = transform.localScale;
        Vector3 mouseScreenPos = Input.mousePosition;
        mouseScreenPos.z = mainCamera.WorldToScreenPoint(Light.transform.position).z;

        // 转换为世界坐标系（XY 平面）
        Vector3 worldPos = mainCamera.ScreenToWorldPoint(mouseScreenPos);
        Vector3 direction = worldPos - Light.transform.position;

        // 计算 Z 轴旋转角度（2D 平面投影）
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        // 应用绕 Z 轴的旋转（保持 X/Y 轴不变）
        Light.transform.rotation = Quaternion.Euler(0, 0, angle);
    }

    private void ChangeCollider()
    {
        if (dir.x != 0)
        {
            _coll.direction = CapsuleDirection2D.Horizontal;
            _coll.size = new Vector2(size.x, size.y);
        }
        else if (dir.y != 0)
        {
            _coll.direction = CapsuleDirection2D.Vertical;
            _coll.size = new Vector2(size.y, size.x);
        }
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Air"))
        {
            AirConsumeManager.Instance.stopConsume = true;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Air"))
        {
            AirConsumeManager.Instance.stopConsume = false;
        }
    }
    
    private void OnStartDive()
    {
        playerInput.Enable();
        transform.position = startPos.position;
    }
    
    private void OnEndDive()
    {
        playerInput.Disable();
        speed = Settings.playerSpeed;
    }
    
    private void OnCarryPeople(GameObject people)
    {
        speed = Settings.carryPeopleSpeed;
    }


    #region useless
    
    private void Jump(InputAction.CallbackContext obj)
    {
        if (check.onGround)
        {
            if (canJump)
            {
                rb.AddForce(jumpForce * transform.up, ForceMode2D.Impulse);
            }
        }
    }

    private void Climb()
    {
        if (check.onStair)
        { 
            //进入攀爬
            if (dir.y != 0 && !stairJump)
            {
                rb.velocity = Vector2.zero;
                rb.MovePosition(transform.position + new Vector3(Settings.climbSpeed.x, Settings.climbSpeed.y * dir.y));
                isClimbing = true;
            }
            else if (check.onGround)
            {
                isClimbing = false;
            }

            if (Input.GetKeyDown(KeyCode.Space) && !stairJump && isClimbing)
            {
                rb.AddForce(Settings.climbForce * new Vector2(dir.x != 0 ? dir.x : transform.localScale.x, 0.5f), ForceMode2D.Impulse);
                stairJump = true;
            }
        }
        else if(check.onStair || check.onGround)
        {
            stairJump = false;
        }

        if (!check.onStair || !isClimbing)
        {
            rb.gravityScale = gravityScale;
            isClimbing = false;
        }
        else if (isClimbing ) rb.gravityScale = 0;
        
    }
    #endregion
    
}
